﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BbsbWebService.Classes;
using BbsbWebService.Enums;
using System.ServiceModel;
using BbsbWebService.Service;
using System.ServiceModel.Web;
using System.ServiceModel.Description;

namespace BbsbWebService.Repositories
{
    public class ClientItemRepository : ItemRepositoryBase
    {
        #region Private Members

        private IBbsbService _service;

        private IBbsbService Service
        {
            get
            {
                if (_service == null)
                {
                    WebChannelFactory<IBbsbService> factory = new WebChannelFactory<IBbsbService>(new Uri(AppSettings.NetworkServerAddress));
                    _service = factory.CreateChannel();
                }

                return _service;
            }
        }

        #endregion

        public override void Initialise()
        {
            var items = Service.GetAllItems();
            foreach (var item in items)
            {
                Items.Add(new ControllableItem
                {
                    Id = item.Id,
                    Name = item.Name,
                    State = item.State,
                    Command = item.Command,
                    Groups = item.Groups
                });
            }
        }

        public override void SaveItem(ControllableItem item)
        {
            Service.SaveItem(item);
        }

        public override void RemoveItem(ControllableItem item)
        {
            Service.RemoveItem(item);
        }

        public override PowerState Toggle(Guid id)
        {
            return Service.Toggle(id);
        }

        protected override void SendPowerBase(ControllableItem item, PowerOption option)
        {
            Service.SendPower(item.Id, option);
        }

        public override void Refresh()
        {
            Items.Clear();
            Initialise();
        }
    }
}
